import socket

# 定义服务器的IP和端口
host = '127.0.0.1'
port = 6666

# 创建 TCP socket
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

def start_server():
    # 绑定 IP 和端口
    server_socket.bind((host, port))
    
    # 开始监听连接
    server_socket.listen(5)  # 最多允许5个待连接的客户端
    print(f"服务器启动，监听 {host}:{port}...")

    try:
        while True:
            # 接受客户端连接
            client_socket, addr = server_socket.accept()
            print(f"连接来自 {addr}")
            
            while True:
                # 接收数据
                data = client_socket.recv(1024)
                if not data:
                    print(f"客户端 {addr} 已断开连接")
                    break  # 退出内层循环，等待下一个客户端
                print(f"收到来自 {addr} 的数据: {data.decode()}")
                
                # 发送确认信息
                response = "数据已接收"
                client_socket.send(response.encode())
            
            # 关闭当前客户端连接
            client_socket.close()
            print(f"关闭与 {addr} 的连接，准备接受下一个连接...")

    except KeyboardInterrupt:
        print("\n服务器正在关闭...")
    finally:
        server_socket.close()
        print("服务器已关闭。")

if __name__ == "__main__":
    start_server()
